package org.sifebint.backend.util;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import flex.messaging.FactoryInstance;
import flex.messaging.FlexFactory;
import flex.messaging.config.ConfigMap;

public class SpringWebContextFactory implements FlexFactory {

	private static final Logger logger = Logger.getLogger(SpringWebContextFactory.class.getName());
	
	public FactoryInstance createFactoryInstance(String name, ConfigMap properties) {
		return new FactoryInstance(this, name, properties);
	}

	public Object lookup(FactoryInstance factoryInstance) {
		
		String beanName = factoryInstance.getProperties().getProperty("source");
		try {
			
			ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(flex.messaging.FlexContext.getServletConfig().getServletContext());
			return appContext.getBean(beanName);
			
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Problem retreiveing bean: " + beanName, e);
			throw new RuntimeException("Problem retreiveing bean: " + beanName, e);
		}
		
	}

	public void initialize(String name, ConfigMap configs) {

	}

}
